import React, { useEffect, useMemo, useState } from "react";
import { Button, Empty, Spin } from "antd";

import { MetaSorted } from "schema-form";
import { SchemaFormContent } from "@/components/schema-form-render/components/schema-form-content";
import { getPageMeta } from "@/services/request/meta";
import ContentSlot from "@/components/schema-form-render/components/schema-form-content/content-solot";
import { getButtons } from "@/utils/with-btns";
import { RollbackOutlined } from "@ant-design/icons";
import {
  formatArrayCollap,
  formatForArrayTable,
  initialSchemaNoraml,
} from "@/components/schema-form-render/utils";
import AnchorPanel from "@/components/schema-form-render/components/page-anchor";
import _ from "lodash";
import { withRouter } from 'umi';
import { registerEvent, useScemaRender } from "../utils";
import { WithNormalHoc } from "hoc-form";
import { FormattedMessage } from "umi";
import { bindLogic } from "@/actionEvent";
import { Form } from "@formily/core/esm/models";
import { useBillParams } from '@/pages/invoice/hooks';

export const HookContext: any = React.createContext<any>({});

export const WithNormalRender: WithNormalHoc = (props) => {
  return withRouter(({ history, ...otherProps }) => {
    const {
      pageCode,
      remoteUrl,
      remoteParams,
      metasConfig,
      needGroup = true,
      type = "NORMAL",
      method = "get",
      nobtns = false,
      needFooter = true,
      initBackBtn = true,
      eventMap = {},
      flag = "",
      modelCode,
      filedConfig = {},
      formConfigs = {},
      dealMetas,
      anchor = false,
      backBtnHook,
      events,
      scenes,
      getInitFormData,
      getMetaWithValue,
      bindLogicParams,
      pageEventsReceiver = (eventsData?: {
        elementCode: string;
        elementTypeCode: string;
        eventName: string;
        imoveProcessCode: string;
        [key: string]: any;
      }) => {}, //接收页面绑定的事件数据
      ...extraProps
    } = _.merge(props, otherProps);
    const { query } = useBillParams(props);

    const refMap = React.useRef();

    const formRef = React.useRef<any>();

    const { form, SchemaFormRender } = useScemaRender(
      filedConfig,
      {
        ...formConfigs,
        effects: (f: Form) => {
          if (formConfigs?.effects) {
            formConfigs.effects(f);
          }
        },
      },
      getInitFormData
        ? () =>
            getInitFormData({
              ...extraProps?.match.params,
              pageCode,
            })
        : null,
      false,
      [pageCode]
    );

    const [mt, setMeta] = useState<any>({});

    const [isLogicLoading, setIsLogicLoading] = useState(false);

    const [loading, setLoading] = useState<boolean>(false);
    const ref = React.useRef<MetaSorted>({});
    const hooksRef = React.useRef<any>({ current: {} });

    const getMeta = async () => {
      if (!pageCode) return offlineData();
      setLoading(true);
      let remoteResult: any = null;
      if (getMetaWithValue) {
        remoteResult = await getMetaWithValue({
          ...extraProps?.match.params,
          pageCode,
        });
      } else {
        remoteResult = await getPageMeta(
          pageCode,
          remoteUrl,
          remoteParams,
          method
        );
      }
      const { success, result } = remoteResult;
      if (remoteResult && remoteResult.result) {
        refMap.current = remoteResult.result?.eventMap || {};
        if (Object.keys(refMap.current || {}).length) {
          setIsLogicLoading(true);
        }
      }
      if (result && scenes) {
        result.scenes = scenes;
      }
      if (success) {
        if (dealMetas) {
          dealMetas(result.pageDatas);
        }

        const sss: any = initialSchemaNoraml(
          _.cloneDeep(result),
          needGroup,
          type,
          eventMap,
          formRef
        );

        await formatForArrayTable(
          sss.ArrayTableList,
          sss.schema,
          type,
          eventMap
        );
        await formatArrayCollap(sss.ArrayColList, sss.schema, type, eventMap);

        ref.current = sss;

        setMeta(sss);
      }
      setLoading(false);
    };

    const getBtns = () => {
      if (nobtns) return [];
      if (sss?.buttons) {
        return getButtons(
          { loading, buttons: sss?.buttons, setLoading },
          hooksRef.current
        );
      }
      return [];
    };

    const handleBack = () => {
      if (backBtnHook) {
        backBtnHook(form, history);
      } else {
        history.goBack();
      }
    };

    const initEvents = () => {
      if (events) {
        registerEvent(hooksRef.current, events, {
          form,
          history,
          match: extraProps?.match,
          setLoading,
        });
      }
    };
    const sss: any = ref.current || {};

    const footer = () => {
      // TODO:是否需要做插入 footer 配置
      if(query?.prcsState==="Reject"){
        const dd = getBtns()?.filter((i:any)=>(i?.key==="tijiao"));
        return (
            <ContentSlot
                left={
                  initBackBtn ? (
                      <Button icon={<RollbackOutlined />} onClick={handleBack}>
                        <FormattedMessage id="config.common.button.back" />
                      </Button>
                  ) : null
                }
                right={dd}
            />
        );
      }
      return (
          <ContentSlot
              left={
                initBackBtn ? (
                    <Button icon={<RollbackOutlined />} onClick={handleBack}>
                      <FormattedMessage id="config.common.button.back" />
                    </Button>
                ) : null
              }
              right={getBtns()}
          />
      );
    };

    const offlineData = async () => {
      setLoading(true);
      if (metasConfig) {
        const sss: any = initialSchemaNoraml(
          _.cloneDeep(metasConfig),
          needGroup,
          type,
          undefined,
          formRef.current
        );

        if (Array.isArray(sss.ArrayTableList) && sss.ArrayTableList?.length) {
          await formatForArrayTable(sss.ArrayTableList, sss.schema, type);
          ref.current = sss;
          setMeta(sss);
          setLoading(false);
        } else {
          ref.current = sss;
          setMeta(sss);
          setLoading(false);
        }
      }
    };
    useEffect(() => {
      if (sss?.columns?.length > 0) {
        initEvents();
      }
      // 执行接受页面事件数据的回调函数，将事件数据传出去
      pageEventsReceiver(sss?.pageConfig?.eventMap);
    }, [sss]);

    useEffect(() => {
      getMeta();
    }, [flag]);

    useEffect(() => {
      if (!form?.id) {
        return;
      }

      formRef.current = form;

      if (Object.keys(refMap.current || {}).length) {
        formRef.current.addEffects("logic", () => {
          bindLogic(refMap.current, {
            payload: {
              ...bindLogicParams,
            },
          });
          setIsLogicLoading(false);
        });
      }
    }, [form?.id, refMap.current]);

    return (
      <HookContext.Provider
        value={{
          hooksRef,
          loading,
          type: "NORMAL",
        }}
      >
        <Spin spinning={loading}>
          {anchor && <AnchorPanel anchorList={sss?.pageConfig?.group || []} />}
          {/*{modelCode && <div style={{ position: 'relative' }}><FormTitle formCode={modelCode} /></div>}*/}
          <SchemaFormContent footer={needFooter ? footer() : null}>
            {sss.columns && sss?.columns?.length > 0 && !isLogicLoading ? (
              <SchemaFormRender
                bizArray={sss.bizArray}
                schema={sss.schema}
                pageConfig={sss?.pageConfig}
              />
            ) : (
              <Empty />
            )}
          </SchemaFormContent>
        </Spin>
      </HookContext.Provider>
    );
  });
};

export const WithNormalComp = WithNormalRender({});
